package com.leo.consumer.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MessageConfig {

    @Bean
    public Queue objectQueue() {
        return new Queue("object.queue");
    }

    /**
     * 配置消息转换器
     */
//    @Bean
    public MessageConverter messageConverter() {
        // 定义消息转换器
        Jackson2JsonMessageConverter converter = new Jackson2JsonMessageConverter(){
            /**
             * 消息转换器，用于将消息转换成对象
             */
            @Override
            public Object fromMessage(Message message) throws MessageConversionException {
                Object header = message.getMessageProperties().getHeader("user-info");
                if (header != null){
                    System.out.println("消息头 -> " + header);
                }
                System.out.println("消息：" + new String(message.getBody()));
                return super.fromMessage(message);
            }
        };
        // 配置自动创建消息ID，用于识别不同消息，也可在业务中基于ID判断是否是重复消息
        converter.setCreateMessageIds(true);
        return converter;
    }
}
